package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.HttpClient;
import com.atguigu.gmall.common.util.HttpClientUtil;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManagerService;
import com.atguigu.gmall.rabbit.constants.MQConst;
import com.atguigu.gmall.rabbit.util.RabbitService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.bytebuddy.asm.Advice;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: lx
 * @Time: 15:57
 * @Description:
 */
@Service
public class ManagerServiceImpl implements ManagerService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        return baseCategory2Mapper.selectList(
                new QueryWrapper<BaseCategory2>().eq("category1_id", category1Id));
    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        return baseCategory3Mapper.selectList(
                new QueryWrapper<BaseCategory3>().eq("category2_id", category2Id));
    }

    //根据一二三级分类ID 查询 平台属性集合
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.attrInfoList(category1Id, category2Id, category3Id);
    }

    //平台属性保存   第一张：平台属性表   第二张 平台属性值表
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //平台属性表
        baseAttrInfoMapper.insert(baseAttrInfo);//主键是自增长  Mysql是集群
        //平台属性值表  外键  上面的表的主键
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        attrValueList.forEach((baseAttrValue) -> {
            //上面的表的主键
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            baseAttrValueMapper.insert(baseAttrValue);
        });

    }

    //查询所有品牌 要求分页
    @Override
    public IPage baseTrademark(Integer page, Integer limit) {
        return baseTrademarkMapper.selectPage(new Page<BaseTrademark>(page, limit), null);
    }

    @Override
    public List<BaseTrademark> getTrademarkList() {
        return baseTrademarkMapper.selectList(null);
    }

    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }


    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    //SPU保存
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //spuInfo对象
        spuInfoMapper.insert(spuInfo);
        //spuImage对象 集合
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)) {
            spuImageList.forEach((spuImage) -> {
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            });
        }
        //spuSaleAttr 集合
        spuInfo.getSpuSaleAttrList().forEach(spuSaleAttr -> {
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);
            //SpuSaleAttrValue 集合
            spuSaleAttr.getSpuSaleAttrValueList().forEach(spuSaleAttrValue -> {
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());//
                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });
        });


    }

    //查询分页结果  SPU商品信息
    @Override
    public IPage<SpuInfo> spuInfoPage(Integer page, Integer limit, Long category3Id) {
        return spuInfoMapper.selectPage(new Page<SpuInfo>(page, limit),
                new QueryWrapper<SpuInfo>().eq("category3_id", category3Id));
    }

    //根据spuId 查询所有图片
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>()
                .eq("spu_id", spuId));
    }

    //根据spuId查询销售属性及属性值
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.spuSaleAttrList(spuId);
    }

    //保存SKU
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        //Sku信息表
        skuInfoMapper.insert(skuInfo);
        //图片表  集合
        skuInfo.getSkuImageList().forEach(skuImage -> {
            skuImage.setSkuId(skuInfo.getId());
            skuImageMapper.insert(skuImage);
        });
        //平台属性表 集合
        skuInfo.getSkuAttrValueList().forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
        //销售属性表 集合
        skuInfo.getSkuSaleAttrValueList().forEach(skuSaleAttrValue -> {
            //商品ID
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            //库存ID
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });
    }

    @Override
    public IPage<SkuInfo> list(Long page, Long limit) {
        return skuInfoMapper.selectPage(new Page<SkuInfo>(page, limit), null);
    }

    @Autowired
    private RabbitService rabbitService;
    //上架
    @Override
    @Transactional
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);
        // update sku_info set is_sale = 1 where id = 4
        //保存库存信息到索引库中
        //发消息  skuId
        rabbitService.sendMessage(MQConst.EXCHANGE_DIRECT_GOODS,
                MQConst.ROUTING_GOODS_UPPER,skuId);

    }

    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);
        //TODO  从索引库中删除库存信息
    }

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    //商品分类 一级 二级 三级  入参：category3_id  URL:随便写  返回值：三级分类名称 不要ID
    @Override
    @GmallCache(prefix="getCategoryView")
    public BaseCategoryView getCategoryView(Long category3id) {
        return baseCategoryViewMapper.selectById(category3id);
    }


    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;//连接Redis

    @Override
    @GmallCache(prefix="getSkuInfo")      //开启事务   1、先进入切面 环绕式方法
    public SkuInfo getSkuInfo(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (null != skuInfo) {
            //根据SkuID查询图片集合
            skuInfo.setSkuImageList(skuImageMapper.
                    selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId)));
        }
        return skuInfo;
    }

   /* @Override
    public SkuInfo getSkuInfo(Long skuId) {
        // 前缀 + 变量 + 后缀
        String cacheKey = RedisConst.SKUKEY_PREFIX +
                skuId + RedisConst.SKUKEY_SUFFIX;
        String lockKey = RedisConst.SKUKEY_PREFIX +
                skuId + RedisConst.SKULOCK_SUFFIX;//sku:1:lock
        //1:先查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (null == skuInfo) {
            try {
                boolean b = redissonClient.getLock(lockKey).
                        tryLock(1, 1, TimeUnit.SECONDS);
                if (b) {
                    //获取到锁
                    //2:如果没有 查询Mysql数据库
                    // select id,name,介绍,category3_id from sku_info where id =
                    skuInfo = skuInfoMapper.selectById(skuId);
                    if (null != skuInfo) {
                        //根据SkuID查询图片集合
                        skuInfo.setSkuImageList(skuImageMapper.
                                selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId)));
                        //备份一份在缓存中  空结果  SkuInfo skuInfo = new SkuInfo();
                        redisTemplate.opsForValue().set(cacheKey, skuInfo,
                                RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(200), TimeUnit.SECONDS);//1天
                    } else {
                        skuInfo = new SkuInfo();//解决缓存穿透问题
                        //  参数3： 过期时间
                        // 参数4：时间单位
                        redisTemplate.opsForValue().set(cacheKey, skuInfo,
                                5, TimeUnit.MINUTES);
                    }
                    redissonClient.getLock(lockKey).unlock();
                } else {
                    //再获取一次缓存
                    try {
                        TimeUnit.SECONDS.sleep(1);
                        skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return skuInfo;
    }*/

    // 库存数据到缓存中  类型？ 五大数据类型   值类型  击穿 分布式锁
   /* @Override
    public  SkuInfo getSkuInfo(Long skuId) {
        // 前缀 + 变量 + 后缀
        String cacheKey = RedisConst.SKUKEY_PREFIX +
                skuId + RedisConst.SKUKEY_SUFFIX;//sku:1:info  硬编码问题  常量  配置文件
        //1:先查询缓存  内存耗尽
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);

        if(null == skuInfo){
            String lockKey = RedisConst.SKUKEY_PREFIX +
                    skuId + RedisConst.SKULOCK_SUFFIX;//sku:1:lock

            String uuid = UUID.randomUUID().toString().replaceAll("-","");

            Boolean ifAbsent = redisTemplate.opsForValue().
                    setIfAbsent(lockKey, uuid,1,TimeUnit.SECONDS);//应急使用此过期时间
            if(ifAbsent){
                //获取到锁
                //2:如果没有 查询Mysql数据库
                // select id,name,介绍,category3_id from sku_info where id =
                skuInfo = skuInfoMapper.selectById(skuId);
                if(null != skuInfo){
                    //根据SkuID查询图片集合
                    skuInfo.setSkuImageList(skuImageMapper.
                            selectList(new QueryWrapper<SkuImage>().eq("sku_id",skuId)));
                    //备份一份在缓存中  空结果  SkuInfo skuInfo = new SkuInfo();
                    redisTemplate.opsForValue().set(cacheKey,skuInfo,
                            RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(200),TimeUnit.SECONDS);//1天
                }else{
                    skuInfo = new SkuInfo();//解决缓存穿透问题
                    //  参数3： 过期时间
                    // 参数4：时间单位
                    redisTemplate.opsForValue().set(cacheKey,skuInfo,
                            5, TimeUnit.MINUTES);
                }
                //解锁  使用UUID防止误删除  不具备原子性操作
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(lockKey), uuid);
            *//*    String o = (String) redisTemplate.opsForValue().get(lockKey);
                if(uuid.equals(o)){
                    redisTemplate.delete(lockKey);//1s
                }*//*
            }else{
                //再获取一次缓存
                try {
                    TimeUnit.SECONDS.sleep(1);
                    skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        //3:有 直接返回
        return skuInfo;
    }*/

    //同学课下自己   人为恶意攻击
    public static void main(String[] args) {
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                HttpClientUtil.doGet("https://item.jd.com/1000103111138198.html");
            }).start();
        }
    }

    @Override
    public BigDecimal getPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        if (null != skuInfo) {
            return skuInfo.getPrice();
        }
        return null;
    }

    //销售属性集合 入参：库存ID skuId  商品ID spuId  返回值 销售属性集合
    @Override
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        return spuSaleAttrMapper.getSpuSaleAttrListCheckBySku(skuId, spuId);
    }

    @Override
    public Map<String, String> getSkuValueIdsMap(Long spuId) {
        Map<String, String> resultMap = new HashMap<>();
        List<Map<String, String>> skuValueIdsMap = skuSaleAttrValueMapper
                .getSkuValueIdsMap(spuId);
        skuValueIdsMap.forEach(skuValueIds -> {
            resultMap.put(skuValueIds.get("value_ids"),
                    String.valueOf(skuValueIds.get("sku_id")));
        });
        return resultMap;
    }
    //查询所有一二三级分类
    @Override
    public List<BaseCategoryView> getCategoryViewList() {
        return baseCategoryViewMapper.selectList(null);
    }

    @Override
    public BaseTrademark getTrademark(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }
    //根据SkuID 查询平台属性及值
    @Override
    public List<SkuAttrValue> getAttrValueList(Long skuId) {

        return skuAttrValueMapper.getAttrValueList(skuId);
    }

    @Override
    public void save(BaseTrademark baseTrademark) {
        baseTrademarkMapper.insert(baseTrademark);
    }

    @Override
    public BaseTrademark edit(Long id) {
        return baseTrademarkMapper.selectById(id);
    }

    @Override
    public void update(BaseTrademark baseTrademark) {
        baseTrademarkMapper.updateById(baseTrademark);
    }
}
